package com.yjz.middleware.redis;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yjz.BaseJunit4Test;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author :yuanJinZhong
 * @description:测试redis的几种数据结构
 * @date :2018/5/23-17:24
 */
public class RedisTest extends BaseJunit4Test {
  private static final Logger log = LoggerFactory.getLogger(RedisTest.class);
  @Autowired
  private RedisTemplate redisTemplate;

  @Test
  public void redistest() throws IOException {
    User u1 = new User();
    u1.setId(1L);
    u1.setName("wang");
    u1.setAge(22);

    /*fastjson 对象转json 很方便*/
    String userString = JSON.toJSONString(u1);

    /*string操作*/
    redisTemplate.opsForValue().set("string操作", userString);

    /*hash操作*/
    redisTemplate.boundHashOps("hash操作").put("name", "wang");
    System.out.println("hash结构取值:" + redisTemplate.opsForHash().get("hash操作", "name"));

    /*list操作*/
    redisTemplate.boundListOps("list操作").leftPush("金忠");

    /*set操作：去重复*/
    redisTemplate.boundSetOps("set操作").add("小龙");
    redisTemplate.boundSetOps("set操作").add("小龙");
    redisTemplate.boundSetOps("set操作").add("小龙2");

    /*zset操作：可排序（带分数的）*/
    redisTemplate.boundZSetOps("zset:这是小明的考试成绩").add("语文", Double.valueOf("99"));
    redisTemplate.boundZSetOps("zset:这是小明的考试成绩").add("数学", Double.valueOf("100"));

    /*fastjson string 转javabean*/
    User user2 = JSON.parseObject(redisTemplate.opsForValue().get("string操作").toString(), User.class);

    /*jackson  string 转javabean*/
    User user = new ObjectMapper().readValue(redisTemplate.opsForValue().get("string操作").toString(), User.class);
    System.out.println(user2.getName());
  }

  @Test
  public void testStringLength() {
    String str = "c6e1d4db86814520bfaedb494a1d46639b1c9edc4c2b407ab32b9c0e60f66a93VZk8Yjn2HzEpmSN8RrDWhiC1pXVMIy4zxLACGAo5vuUpYve2sS52kAHeyVfUUkdYJ9bErNRNs/g3MRlxGFJ97ypqeXmSnF6dwIlVfndJ3d+5g+LTpKB9zRk3/VbXZhaz23U2sQeOnILbAa0u45mdkmc2WuAVmQq3Zg5ke8ZqhK9QBcYelAznLwdi2kYH91enG6I8ALIDAIviQshJHagO6JYVI16Lytp32eZn+icuery/DeeJxFd1CPasQqETmhsI/g3MRlxGFJ97ypqeXmSnF6dwIlVfndJ3d+5g+LTpKB9zRk3/VbXZhaz23U2sQeOnILbAa0u45mdkmc2WuAVmQq3Zg5ke8ZqhK9QBcYelAznLwdi2kYH91enG6I8ALIDAIviQshJHagO6JYVI16Lytp32eZn+icuery/DeeJxFd1CPasQqETmhsI";
    System.out.println(str.length());
  }

  public static void main(String[] args) {
    Jedis jedis = new Jedis("192.168.59.128", 6379);
    System.out.println("连接成功");
    //查看服务是否运行
    System.out.println("服务正在运行: " + jedis.ping());
    jedis.set("test", "这是string测试！");
    System.out.println(jedis.get("test"));
  }


  public void redisIncrement() {
    Long currentValue = redisTemplate.opsForValue().increment("yjz", 1L);
    if (currentValue == 100L) {
      log.info("增加100次了");
    }
  }

  /**
   * @description: redis String 累加 和过期
   * @author :yuanJinZhong
   * @date :2018/7/31-10:38
   */
  @Test
  public void redisIncrementTest() throws InterruptedException {
    ExecutorService executorService = Executors.newFixedThreadPool(20);
    CountDownLatch countDownLatch = new CountDownLatch(100);
    for (int i = 0; i < 100; i++) {
      executorService.submit(() -> {
        Long currentValue = redisTemplate.opsForValue().increment("yjz", 1L);
        log.info("任务执行");
        if (currentValue == 100L) {
          log.info("增加100次了");
          redisTemplate.expire("yjz", 60L, TimeUnit.SECONDS);
        }
        countDownLatch.countDown();
      });
    }
    countDownLatch.await();
    log.info("100个任务执行结束  ");
  }

  @Test
  public void redisListTest() {
//		list操作
    ListOperations<String, String> listOps = redisTemplate.opsForList();
//		listOps.leftPush("myList","袁金忠");
//		listOps.leftPush("myList","张三");
//		listOps.leftPush("myList","李四");
//		listOps.leftPush("myList","王五");
//		String value= listOps.leftPop("myList");
//		log.info(value);
//		listOps.remove("myList",0,null);
    List list = new ArrayList();
    list.add("1");
    list.add("2");
    list.add("3");
    list.add("4");
    list.add("5");

//		listOps.leftPushAll("myList2",list);
//	   List mylist=	listOps.range("myList2",0,-1);
//	   log.info(mylist+"");
    //从0开始删除指定key 里面的指定值（有多少删多少）
    listOps.remove("myList", 0, "袁金忠");

    /*zset操作：可排序（带分数的）*/
//		redisTemplate.boundZSetOps("zset:这是小明的考试成绩").add("语文", Double.valueOf("99"));
//		redisTemplate.boundZSetOps("zset:这是小明的考试成绩").add("数学", Double.valueOf("100"));


    /*set操作：去重复*/
//		redisTemplate.boundSetOps("set操作").add("小龙");
//		redisTemplate.boundSetOps("set操作").add("小龙");
//		redisTemplate.boundSetOps("set操作").add("小龙2");

//		hash操作
    HashOperations hashOperations = redisTemplate.opsForHash();

    hashOperations.put("学生成绩单", "张三", "99");
    hashOperations.put("学生成绩单", "李四", "22");

    hashOperations.put("学生成绩单", "王五", "44");

    hashOperations.put("学生成绩单", "霍元甲", "55");

    Map<String, String> map = hashOperations.entries("学生成绩单");

    log.info(map + "");
  }


}
